package cn.wolfcode.crm.service.impl;

import cn.wolfcode.crm.domain.Employee;
import cn.wolfcode.crm.domain.Role;
import cn.wolfcode.crm.mapper.EmployeeMapper;
import cn.wolfcode.crm.query.QueryObject;
import cn.wolfcode.crm.service.IEmployeeService;
import cn.wolfcode.crm.util.PageResult;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;
@Service
public class EmployeeServiceImpl implements IEmployeeService {

    @Autowired
    private EmployeeMapper employeeMapper;

    @Override
    public void deleteByPrimaryKey(Long id) {
        employeeMapper.deleteByPrimaryKey(id);
    }

    @Override
    public Employee selectByPrimaryKey(Long id) {
        return employeeMapper.selectByPrimaryKey(id);
    }

    @Override
    public List<Employee> selectAll() {
        return employeeMapper.selectAll();
    }

    @Override
    public void saveOrUpdate(Employee entity) {
        if (entity.getId() != null){
            employeeMapper.deleteRoleByEmpId(entity.getId());
            employeeMapper.updateByPrimaryKey(entity);
        }else {
            Md5Hash md5Hash = new Md5Hash(entity.getPassword(), entity.getUsername(), 2);
            entity.setPassword(md5Hash.toString());
            entity.setState(true);
            employeeMapper.insert(entity);
        }
        List<Role> roles = entity.getRoles();
        for (Role role : roles) {
            employeeMapper.insertByRoleIdAndEmpId(role.getId(),entity.getId());
        }
    }

    @Override
    public PageResult query(QueryObject qo) {
        int total = employeeMapper.query4Count(qo);
        if(total == 0 ){
            return new PageResult(0, Collections.EMPTY_LIST);
        }
        List<Employee> rows = employeeMapper.query4List(qo);
        return new PageResult(total,rows);
    }

    @Override
    public void changeState(Long id) {
        employeeMapper.changeState(id);
    }

    @Override
    public void changePwd(String password,Long id) {
        Employee entity = employeeMapper.selectByPrimaryKey(id);
        Md5Hash md5Hash = new Md5Hash(password, entity.getUsername(), 2);
        employeeMapper.changePwd(md5Hash.toString(),id);
    }

    @Override
    public void insert(Employee employee) {
        employeeMapper.insert(employee);
    }

    @Override
    public List<Employee> listAll() {
        return employeeMapper.listAll();
    }
}
